package com.aidex.framework.mybatis.handler;

import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author su
 * @Date 2021/11/21 18:39
 */
@Component
public class FillMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        if (this.getFieldValByName("status", metaObject) == null) {
            this.setFieldValByName("status", "0", metaObject);
        }
        this.setFieldValByName("delFlag", "0", metaObject);
        this.setFieldValByName("version", 1, metaObject);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (null != loginUser.getUser()) {
            this.setFieldValByName("createBy", loginUser.getUser().getId(), metaObject);
            this.setFieldValByName("createDept", loginUser.getUser().getDeptId(), metaObject);
        } else {
            this.setFieldValByName("createBy", "1", metaObject);
            this.setFieldValByName("createDept", "100", metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (this.getFieldValByName("version", metaObject) != null) {
            this.setFieldValByName("version", (Integer) metaObject.getValue("version") + 1, metaObject);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (null != loginUser.getUser()) {
            this.setFieldValByName("updateBy", loginUser.getUser().getId(), metaObject);
            this.setFieldValByName("updateIp", loginUser.getIpaddr(), metaObject);
        } else {
            this.setFieldValByName("updateBy", "1", metaObject);
            this.setFieldValByName("updateIp", "127.0.0.1", metaObject);
        }
    }
}
